package udf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import domain.Access;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import utils.StringUtils;

import java.io.IOException;

/**
 * Create by zhh on 2022/9/9.
 * 在Access里面增加了从高德中通过网页请求获得的IP定位得到的省份和城市
 */
public class GaodeLocationMapFunction extends RichMapFunction<Access, Access> {
    CloseableHttpClient httpClient;
    @Override
    public void open(Configuration parameters) throws Exception {
        httpClient=HttpClients.createDefault();//创建HTTP连接
    }

    @Override
    public void close() throws Exception {
        if (httpClient!=null) httpClient.close();//关闭HTTP连接
    }

    @Override
    public Access map(Access access) throws Exception {
        String url="https://restapi.amap.com/v3/ip?ip="+access.ip+"&output=json&key="+ StringUtils.GAODE_KEY;
        String province = "-";//省份，若未取到则为-，防止为空
        String city = "-";//城市，若未取到则为-，防止为空
        CloseableHttpResponse response = null;
        try {

            HttpGet httpGet = new HttpGet(url);//连接url
            response = httpClient.execute(httpGet);//获取respose
            int statusCode = response.getStatusLine().getStatusCode();//状态码
            if (statusCode==200){
                HttpEntity entity = response.getEntity();//获取实体
                String result = EntityUtils.toString(entity);//获取实体内容
                JSONObject jsonObject = JSON.parseObject(result);//解析json文件
                province = jsonObject.getString("province");//得到省份
                city = jsonObject.getString("city");//得到城市
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            response.close();
            access.province=province;//将省份变量赋值给Access类中的province
            access.city=city;//将城市变量赋值给Access类中的city
        }
        return access;//返回添加了IP相应位置的Access
    }
}
